// @ts-nocheck
/**
 * @Date: 2022-04-11 11:17:13
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-15 20:51:54
 * @FilePath: \weibo-api\controller\blogCtl.js
 * @Description: 微博数据处理
 */
const { Blog, User, AtBlog, Topic, Reply } = require("../model/index");
const { SuccessModel, ErrorModel } = require("../ResModel");
const { analysis, DelBlogWithImg } = require("../tools");
const xss = require("xss");
const REG_AT = /@(.+?)\s-\s(\w+?)\b/g;

//创建博客
const createBlog = async (ctx, next) => {
  let newBlog = {};
  let { content, imageUrl } = ctx.request.body;
  //获取用户@的id列表
  const userIdList = analysis(content, REG_AT);
  //预防xss
  content = xss(content);
  //匹配 @符号
  content = content.replace(REG_AT, (itemStr, nickName, atUserId) => {
    // console.log(itemStr, nickName, atUserId);
    return `<a href="/personal/${atUserId}" class="aitem">@${nickName}</a>`;
  });
  newBlog.content = content;
  newBlog.userId = ctx.session.userInfo.id;
  if (imageUrl) {
    newBlog.imageUrl = imageUrl;
  }

  try {
    let newWeiBo = await Blog.create(newBlog);
    if (newWeiBo.dataValues.imageUrl) {
      newWeiBo.dataValues.imageUrl = JSON.parse(newWeiBo.dataValues.imageUrl);
    }
    //创建 @ 关系
    if (userIdList.length !== 0) {
      await Promise.all(
        userIdList.map(async (userId) => {
          try {
            let res = await AtBlog.create({
              userId,
              blogId: newWeiBo.dataValues.id,
            });
            return res.dataValues;
          } catch (error) {
            console.error("出错了", error);
          }
        }),
      );
    }

    ctx.body = new SuccessModel(newWeiBo.dataValues);
  } catch (error) {
    console.error(error);
    ctx.throw(500, "创建失败！，请稍后重试" + error);
  }
};
//获取用户的博客列表
const getBlogList = async (ctx, next) => {
  let { currentPage = 1, pageSize = 5, id } = ctx.query;
  currentPage = parseInt(currentPage);
  pageSize = parseInt(pageSize);
  const userWhereOpt = {};
  if (id) {
    userWhereOpt.id = id;
  }
  const res = await Blog.findAndCountAll({
    limit: pageSize, //每页条数
    offset: (currentPage - 1) * pageSize, //跳过条数
    order: [["id", "desc"]],
    include: [
      {
        model: User,
        attributes: ["id", "userName", "nickName", "avatar"],
        where: userWhereOpt,
      },
    ],
  });
  // res.count 总数 res.rows查询结果数组
  let blogList = res.rows.map((row) => row.dataValues);
  blogList = blogList.map((blogItem) => {
    blogItem.imageUrl = JSON.parse(blogItem.imageUrl);
    const user = blogItem.user.dataValues;
    blogItem.user = user;
    return blogItem;
  });
  // console.log("最终结果", blogList);
  ctx.body = new SuccessModel({
    count: res.count,
    blogList,
  });
};
//获取广场博客列表
const getSquareList = async (currentPage, pageSize) => {
  const res = await Blog.findAndCountAll({
    limit: pageSize, //每页条数
    offset: (currentPage - 1) * pageSize, //跳过条数
    order: [["id", "desc"]],
    include: [
      {
        model: User,
        attributes: ["id", "userName", "nickName", "avatar"],
      },
    ],
  });
  // res.count 总数 res.rows查询结果数组
  let blogList = res.rows.map((row) => row.dataValues);
  blogList = blogList.map((blogItem) => {
    blogItem.imageUrl = JSON.parse(blogItem.imageUrl);
    const user = blogItem.user.dataValues;
    blogItem.user = user;
    return blogItem;
  });
  return {
    count: res.count,
    blogList,
  };
};
//删除博客
const deleteBlog = async (ctx, next) => {
  const { id: blogId } = ctx.params;
  let blog = await Blog.findOne({ where: { id: blogId } });
  const res = await Blog.destroy({
    where: { id: blogId },
  });
  // console.log(res);
  DelBlogWithImg(blog.dataValues.imageUrl);
  if (res > 0) {
    ctx.body = new SuccessModel();
  } else {
    ctx.body = new ErrorModel(500, `删除失败！`);
  }
};
//获取单个博客详情
const blogDetail = async (ctx, next) => {
  const { blogId, userId } = ctx.params;
  const whereOpt = {};
  if (userId != -1) {
    whereOpt.id = userId;
  }
  let blog = await Blog.findOne({
    attributes: ["id", "content", "imageUrl", "createdAt"],
    include: [
      {
        model: User,
        attributes: ["id", "userName", "nickName", "avatar"],
        where: whereOpt,
      },
    ],
    where: { id: blogId },
  });
  if (blog !== null) {
    ctx.body = new SuccessModel(blog.dataValues);
    return;
  }
  ctx.body = new ErrorModel(404, "查询失败");
};
module.exports = {
  createBlog,
  getBlogList,
  getSquareList,
  deleteBlog,
  blogDetail,
};
